import Dish from '../models/Dish.js';  // 引入模型
import Ingredient from '../models/Ingredient.js';  // 引入模型

export default class DishController {
  // 获取菜品列表（带分页）
  static async list(ctx) {
    const { page = 1, pageSize = 10 } = ctx.query;
    const skip = (page - 1) * pageSize;

    const [dishes, total] = await Promise.all([
      Dish.find()
        .populate('purchaser chefId')
        .populate('requiredIngredients.ingredient')
        .skip(skip)
        .limit(Number(pageSize)),
      Dish.countDocuments()
    ]);

    ctx.body = {
      data: dishes,
      pagination: {
        page: Number(page),
        pageSize: Number(pageSize),
        total
      }
    };
  }

  // 创建菜品（带事务处理）
  static async create(ctx) {
    // 从请求体中解构必要字段
    const {
      dishName,
      mealType,
      requiredIngredients,
      chefId,
      ...otherFields
    } = ctx.request.body;

    // 基础校验（模型层验证仍会生效，此处做前置校验）
    if (!dishName || !mealType) {
      ctx.throw(400, '必填字段缺失');
    }

    // 创建新菜品文档（带事务会话）
    const newDish = {
      dishName,
      mealType,
      chefId: chefId || null,  // 允许可选字段
      // requiredIngredients: requiredIngredients.map(ing => ({
      //   ingredient: ing.ingredient,
      //   quantity: Number(ing.quantity.toFixed(2))
      // })),
      createdBy: ctx.state.userId,  // 假设中间件已注入用户ID
      // ...otherFields
    };
    // 保存文档（带事务控制）
    const savedDish = await Dish.insertOne(newDish);
    console.log('🚀 ~ savedDish:', savedDish);
    if (!savedDish) {
      ctx.body = {
        status: 500,
        msg: "创建失败"
      };
    }else{
      ctx.body = {
        status: 200,
        data: {name:savedDish.dishName, id:savedDish._id},
        msg: "创建成功"
      };
    }
  }

  // 更新菜品状态
  static async updateStatus(ctx) {
    const { id } = ctx.params;
    const { cookingStatus } = ctx.request.body;

    const updated = await Dish.findByIdAndUpdate(
      id,
      { cookingStatus },
      { new: true, runValidators: true }
    ).populate('purchaser chefId');

    if (!updated) ctx.throw(404, 'Dish not found');
    ctx.body = updated;
  }

  // 档案列表
  static async archives(ctx) {
    return Ingredient.find().then((data) => {
      ctx.body = {
        data: data,
        status: 200,
        msg: '获取成功'
      };
    }).catch(err => {
      ctx.body = {
        data: [],
        status: 500,
        msg: `获取失败: ${err}`
      };
    })

  }
}